import React, { FC, useCallback, useEffect, useRef, useState } from "react";
import { ContextMenu, MenuItem } from "react-contextmenu";
import { useGetWallpapersQuery, getWallpaperByName } from '@services/wallpaper';
import SearchBar from '@components/searchbar';
import { Pagination, Image } from 'antd';
import { ContextMenuData, ContextMenuItem, Wallpaper, WallpaperQuality } from '@interfaces';
import Card from '@components/card';
import Empty from '@components/empty';
import './index.scss';
import { debounce } from "lodash";
import { AppstoreOutlined, CloudDownloadOutlined, FundViewOutlined } from "@ant-design/icons";

interface WallpaperProps {
  wallpaperType?: string;
}

const Wallpaper: FC<WallpaperProps> = (props: WallpaperProps) => {
  const { wallpaperType } = props;
  const [pageNo, setpageNo] = useState<number>(1);
  const [limit, setLimit] = useState<number>(12);
  const [keyword, setKeyword] = useState<string>('');
  const { data: response } = useGetWallpapersQuery({
    pageNo,
    limit,
    keyword,
    type: wallpaperType,
  });

  const onPaginationChange = useCallback((pageNo, pageNoSize) => {
    setpageNo(pageNo);
    setLimit(pageNoSize);
  }, [setpageNo, setLimit]);

  const onSearch = useCallback(debounce((value) => {
    setKeyword(value);
  }, 500), []);


  const [visible, setVisible] = useState<boolean>(false);
  const [previewImageURL, setPreviewImageURL] = useState<string>('');

  const contextmenus: Array<ContextMenuItem> = useRef([{
    icon: <CloudDownloadOutlined />,
    label: '下载',
    onClick: async (event: Event, data: ContextMenuData) => {
      const { target } = data;
      const { name } = target.dataset;
      if (target.dataset._id) {
        try {
          const { uri, external } = await getWallpaperByName(name, WallpaperQuality.High);
          if (uri) {
            const fileName = `${name}${external}`;
            // downloadFile(uri, fileName, app.getPath('downloads'));
            new Notification("通知", {
              body: `壁纸${fileName}下载成功`,
            });
          }
        } catch (error) {
          new Notification("通知", {
            body: `壁纸下载失败`,
          });
          console.error(error);
        }
      }
    },
  }, {
    icon: <FundViewOutlined />,
    label: '预览',
    onClick: async (event: Event, data: ContextMenuData) => {
      const { target } = data;
      console.log(target);
      const { name } = target.dataset;
      if (target.dataset._id) {
        const { uri } = await getWallpaperByName(name, WallpaperQuality.Middle);
        if (uri) {
          setPreviewImageURL(uri);
          setVisible(true);
        }
      }
    },
  }, {
    icon: <AppstoreOutlined />,
    label: '设为壁纸',
    onClick: async (event: Event, data: ContextMenuData) => {
      const { target } = data;
      const { name } = target.dataset;
      if (target.dataset._id) {
        let wallpaperDownloadPath = '';
        try {
          const { uri } = await getWallpaperByName(name, WallpaperQuality.High);
          wallpaperDownloadPath = uri;
        } catch (error) {
          const { uri } = await getWallpaperByName(name, WallpaperQuality.Middle);
          wallpaperDownloadPath = uri;
        } finally {
          if (wallpaperDownloadPath) {
            // ipcRenderer.send("download", wallpaperDownloadPath); // 下载
            new Notification("通知", {
              body: "壁纸设置成功",
            });
          } else {
            new Notification("通知", {
              body: "壁纸设置失败",
            });
          }
        }
      }
    },
  }]).current;

  useEffect(() => {
    // ipcRenderer.on('download-done', async (event, filePath) => {
    //   await wallpaper.set(filePath);
    // })
  }, [])

  return <div className="wallpaper-outer">
    <div className="wallpaper-head">
      <SearchBar value={keyword} onChange={onSearch} />
    </div>
    {
      response?.data?.rows?.length ? (
        <React.Fragment>
          <div className="wallpaper-body">
            {
              (response?.data.rows || []).map((row: Wallpaper) => <Card key={row._id} {...row} />)
            }
          </div>
          <div className="wallpaper-foot">
            <Pagination
              size="small"
              onChange={onPaginationChange}
              defaultCurrent={pageNo}
              pageSize={limit}
              pageSizeOptions={[12, 24, 48, 96]}
              total={response?.data.total || 0}
              showSizeChanger
              showQuickJumper />
          </div>
          <ContextMenu id="same_unique_identifier">
            {
              (contextmenus||[]).map((c, i) => <MenuItem key={i} className="menu-item" onClick={c.onClick}>{c.icon}  {c.label}</MenuItem>)
            }
          </ContextMenu>
          <Image
            preview={{
              visible,
              src: previewImageURL,
              onVisibleChange: value => {
                setPreviewImageURL('');
                setVisible(value);
              },
            }}
          />
        </React.Fragment>
      ) : <Empty />
    }
  </div>
}

export default Wallpaper;
